package com.logtoolkit.util;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public final class DateTimeUtil {

    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String format(Date date) {
        return format(date, null);
    }

    public static String format(Date date, String pattern) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern(StringUtils.isBlank(pattern) ? DEFAULT_PATTERN : pattern));
    }

    public static Date parse(String timeStr) {
        return parse(timeStr, null);
    }

    public static Date parse(String timeStr, String pattern) {
        return Date.from(LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(StringUtils.isBlank(pattern) ?
                DEFAULT_PATTERN : pattern)).atZone(ZoneId.systemDefault()).toInstant());
    }

}
